//
//  DuanZiViewController.m
//  ProJectB_1
//
//  Created by lanou3g on 16/8/12.
//  Copyright © 2016年 yangshukai. All rights reserved.
//

#warning 段子2
#import "DuanZiViewController.h"
#import "DuanZiCell.h"
#import "DuanZiModel.h"
#import "AFNetworking.h"
#import "MJRefresh.h"



static NSString *url1 = @"http://s.budejie.com/topic/tag-topic/64/hot/bs0315-iphone-4.3/";
static NSString *url2 = @"-20.json";
typedef enum {
    DuanZiTypeAll = 1,
    DuanZITypePicture = 10,
    DuanZiTypeword= 29,
    DuanZiTypeperrideo = 35
    
    
}DuanZiType;

@interface DuanZiViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) UITableView *duaziTableView;

@property (nonatomic,strong)DuanZiModel *duanziModel;
@property (nonatomic,assign)DuanZiType type;


@property (nonatomic,strong)NSMutableDictionary *params;
@property (nonatomic,assign)NSInteger page;
@property (nonatomic,copy)NSString *maxtime;
@property (nonatomic,strong) NSString *urlString;
@end
static NSString *iden =@"cell";
@implementation DuanZiViewController
- (NSMutableArray *)dataArray{
    
    
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    //    self.view.backgroundColor = [UIColor blueColor];
    self.title = @"段子";
    
    self.dataArray = [NSMutableArray array];
    self.type = 29;
    self.duaziTableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:(UITableViewStylePlain)];
    _duaziTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _duaziTableView.delegate = self;
    _duaziTableView.dataSource = self;
    //    [tableView registerNib:[UINib nibWithNibName:@"DuanZiCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:iden];
    [_duaziTableView registerClass:[DuanZiCell class] forCellReuseIdentifier:iden];
    
    [self.view addSubview:self.duaziTableView];
    
    
    //    [tableView registerClass:[DuanZiCell class] forHeaderFooterViewReuseIdentifier:iden];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"退出" style:(UIBarButtonItemStylePlain) target:self action:@selector(back:)];
    
    //添加刷新控件
    [self setupRefresh];
}

- (void)back:(id)sender{
    DrawerViewController *menuController = (DrawerViewController*)((AppDelegate *)[[UIApplication sharedApplication] delegate]).rootTabBarViewController.drawerController;
    [menuController dismissViewControllerAnimated:YES completion:nil];
}

//上下拉刷新
- (void)setupRefresh{
    
    self.duaziTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopics)];
    self.duaziTableView.header.automaticallyChangeAlpha = YES;
    //一进页面就刷新
    [self.duaziTableView.header beginRefreshing];
    
    //上拉刷新
    self.duaziTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopics)];
    
}





- (void)loadNewTopics{
    
    //发送数据给服务器
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    self.params =params;
    
    
    
    __weak typeof( self)weakSelf =self;
    
    [[AFHTTPSessionManager manager]GET:@"http://s.budejie.com/topic/tag-topic/64/hot/bs0315-iphone-4.3/0-20.json" parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
        //        NSLog(@"_______________------%@",responseObject);
        if (weakSelf.params != params) {
            return ;
        }
        
        weakSelf.page =0;
        weakSelf.urlString = responseObject[@"info"][@"np"];
        NSArray *array = responseObject[@"list"];
        [weakSelf.dataArray removeAllObjects];
        for (NSDictionary *dic in array) {
            DuanZiModel *model = [[DuanZiModel alloc]init];
            NSDictionary *diction = dic[@"u"];
            NSArray *arr = diction[@"header"];
            model.header = arr.lastObject;
            model.name = diction[@"name"];
            model.passtime = dic[@"passtime"];
            model.text = dic[@"text"];
            model.up = dic[@"up"];
            model.down = dic[@"down"];
            model.forward = dic[@"forward"];
            model.comment = dic[@"comment"];
            [weakSelf.dataArray addObject:model];
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [weakSelf.duaziTableView reloadData];
            [weakSelf.duaziTableView.header endRefreshing];
            weakSelf.page = 0;
            
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(weakSelf.params != params)return;
        [weakSelf.duaziTableView.header endRefreshing];
        
    }];
}







-(void)loadMoreTopics {
    
    [self.duaziTableView.header endRefreshing];
    self.page ++;
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    params[@"page"] =@(self.page);
    
    self.params =params;
    
    __weak typeof( self)weakSelf =self;
    
    [[AFHTTPSessionManager manager]GET:[NSString stringWithFormat:@"%@%@%@", url1, weakSelf.urlString, url2] parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
        NSLog(@"%@", responseObject);
        if (weakSelf.params != params) {
            return ;
        }
        
        weakSelf.maxtime = responseObject[@"info"][@"maxtime"];
        
        weakSelf.urlString = responseObject[@"info"][@"np"];
        
        NSArray *array = responseObject[@"list"];
        for (NSDictionary *dic in array) {
            DuanZiModel *model = [[DuanZiModel alloc]init];
            NSDictionary *diction = dic[@"top_comment"];
            NSArray *arr = diction[@"u"][@"header"];
            model.header = arr[0];
            model.name = diction[@"u"][@"name"];
            model.passtime = dic[@"passtime"];
            model.text = dic[@"text"];
            model.up = dic[@"up"];
            model.down = dic[@"down"];
            model.forward = dic[@"forward"];
            model.comment = dic[@"comment"];
            [weakSelf.dataArray addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [weakSelf.duaziTableView reloadData];
            [weakSelf.duaziTableView.footer endRefreshing];
            weakSelf.page = 0;
            
            //            NSLog(@"%@", weakSelf.dataArray);
            
        });
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if(weakSelf.params != params)return;
        
        [weakSelf.duaziTableView.footer endRefreshing];
        
        weakSelf.page --;
    }];
    
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    //    NSLog(@"%ld=====================", self.dataArray.count);
    return self.dataArray.count;
    
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DuanZiModel *model = self.dataArray[indexPath.row];
    NSString *text = model.text;
    NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:13]};
    CGSize size = [text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 20, 1000000) options: NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    
    CGFloat heig = size.height;
    return 10 + 40 + 20 + heig + 20 + 40;
    
    
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DuanZiCell *cell = [tableView dequeueReusableCellWithIdentifier:iden forIndexPath:indexPath];
    DuanZiModel *DuanZi = self.dataArray[indexPath.row];
    cell.model = DuanZi;

    
       
    return cell;
}

@end
